<template>
    <van-form @submit="onSubmit">
        <van-cell-group inset>
            <van-field v-model="addTeamData.teamName" name="teamName" label="队伍名称" placeholder="请输入队伍名称"
                :rules="[{ required: true, message: '请输入队伍名称' }]" />
            <van-field v-model="addTeamData.description" rows="4" autosize label="队伍描述" type="textarea"
                placeholder="请输入队伍描述" :rules="[{ required: true, message: '请输入队伍描述' }]" />

            <van-field v-model="addTeamData.expireTime" is-link readonly name="datePicker" label="过期时间"
                placeholder="点击选择过期时间" @click="showPicker = true" :rules="[{ required: true, message: '请选择队伍过期时间' }]" />

            <van-field name="logo" label="队伍logo">
                <template #input>
                    <van-uploader v-model="fileList" multiple :max-count="1" />
                </template>
            </van-field>

            <van-popup v-model:show="showPicker" position="bottom">
                <van-date-picker @confirm="onConfirm" @cancel="showPicker = false" :min-date="minDate" />
            </van-popup>

            <van-field name="stepper" label="最大人数">
                <template #input>
                    <van-stepper v-model="addTeamData.maxNum" max="20" min="3" />
                </template>
            </van-field>
        </van-cell-group>

        <div style="margin: 16px;">
            <van-button round block type="primary" native-type="submit">
                提交
            </van-button>
        </div>
    </van-form>
</template>

<script setup>
import { useRouter } from "vue-router";
import { ref } from "vue";
import request from "../utils/axios.ts";
import { ImageToBase64 } from "@/utils/ImgToBase64.ts";

const router = useRouter();
const fileList = ref([])
const minDate = new Date()
const initFormData = {
    "description": "",
    "expireTime": "",
    "maxNum": 3,
    "avatarUrl": "",
    "teamName": "",
    "userId": 0,
};

// 需要用户填写的数据
const addTeamData = ref({ ...initFormData }); // 拓展对象运算符

const showPicker = ref(false);
const onConfirm = ({ selectedValues }) => {
    addTeamData.value.expireTime = selectedValues.join('-')
    showPicker.value = false;
};

const onSubmit = async () => {
    const imgUrl = await ImageToBase64(fileList.value[0])
    addTeamData.value.avatarUrl = imgUrl
    const postData = addTeamData.value
    // todo 前端参数校验
    const res = await request.post('/team/add', postData);
    if (res.data) {
        showSuccessToast("成功创建队伍");
        router.push({
            path: "/team",
            replace: true
        })
    } else {
        showFailToast("创建队伍失败！");
    }
}

</script>

<style scoped></style>